package org.shan.lis.common.serial;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

import java.util.ArrayList;
import java.util.Enumeration;

public class SerialFactory {
	
	public static ArrayList<String> listPortChoices() {
        CommPortIdentifier portId;
        ArrayList<String> serialNames = new ArrayList<String>();
        
        Enumeration en = CommPortIdentifier.getPortIdentifiers();
        // iterate through the ports.
        while (en.hasMoreElements()) {
            portId = (CommPortIdentifier) en.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            	serialNames.add(portId.getName());
            }
            System.out.println(portId.getName());
        }
        
        return serialNames;
    }
	
	public static SerialPort openSerial(SerialParameters serialParameters)
	{
		SerialPort serialPort;
		CommPortIdentifier portId;
		Enumeration en = CommPortIdentifier.getPortIdentifiers();
        // iterate through the ports.
        while (en.hasMoreElements()) {
            portId = (CommPortIdentifier) en.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            	if (portId.getName().equals(serialParameters.getPortName()))
            	{
                    try {
                        serialPort = (SerialPort) portId.open("MPTPCSERIAL", 1000);
                        serialPort.notifyOnDataAvailable(true);
                        try {

                            serialPort.setSerialPortParams(
                            	serialParameters.getBaudRate(),
                            	serialParameters.getDatabits(),
                            	serialParameters.getStopbits(),
                            	serialParameters.getParity());

                            serialPort.setFlowControlMode(serialParameters.getFlowControlIn());
                        } catch (UnsupportedCommOperationException e) {}
                        return serialPort;
                    } catch (PortInUseException e){
                    	System.out.println(e);
                    }
            	}
            }
        }
        return null;
	}
	
	public static void SetSerialParams(SerialPort serialPort, SerialParameters serialParameters)
	{
        try {
            serialPort.setSerialPortParams(
            	serialParameters.getBaudRate(),
            	serialParameters.getDatabits(),
            	serialParameters.getStopbits(),
            	serialParameters.getParity());
        } catch (UnsupportedCommOperationException e) {}
	}

    public static void main(String[] args) {
        listPortChoices();
    }

}
